<template>
    <div>
        <header>
            <div class="tabEditWrapper">
                <el-tabs :closable="editControl[0] && userInfo.authBtn.includes('/platform/del')" v-model="activeShop"
                         type="card" @tab-remove="name=>handleRemove({platform:name},'platform')"
                         @tab-click="tab=>handleClick(tab,0)">
                    <el-tab-pane v-for="i in platformData" :key="i.value" :label="i.label"
                                 :name="i.value"></el-tab-pane>
                </el-tabs>
                <div class="tabSwitch" v-if="editControl[0] && userInfo.authBtn.includes('/food/upload')">
                    <el-form :size="customStyle.size" v-if="userInfo.authBtn.includes('/platform/set')" label-width="150px"
                             ref="validateFormShop_0" class="outerForm" :model="sendFormData.shop"
                             :rules="rules.shop">
                        <el-form-item :label="`${currentShop.label || ''}起送价`" prop="step">
                            <el-input clearable placeholder="请输入起送价" v-model.number="sendFormData.shop.step"
                                      autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label-width="20px">
                            <el-button type="primary" @click="handleSave('platform_0')">保 存</el-button>
                        </el-form-item>
                    </el-form>
                    <el-button type="primary" :size="customStyle.size" @click="handleUpload()">
                        {{$i18n.t('btnControl./shop.uploadMenu')}}
                    </el-button>
                </div>
            </div>
            <div class="tabEditWrapper">
                <el-tabs :closable="editControl[0] && userInfo.authBtn.includes('/tag/del')"
                         @tab-remove="name=>handleRemove({tag:name},'classify')" v-model="activeTab"
                         @tab-click="tab=>handleClick(tab,1)">
                    <el-tab-pane :disabled="editControl[0]" label="全部" name="全部"></el-tab-pane>
                    <el-tab-pane v-for="i in tagData" :key="i" :label="i" :name="i"></el-tab-pane>
                </el-tabs>
                <div class="tabSwitch">
                    <el-checkbox
                        v-if="userInfo.authBtn.includes('/platform/set') || userInfo.authBtn.includes('/tag/set')"
                        @change="v=>v && (editControl[1]=false)" v-model="editControl[0]">
                        {{$i18n.t('btnControl./shop.editClassify')}}
                    </el-checkbox>
                    <el-checkbox v-if="userInfo.authBtn.includes('/food/set')" @change="v=>v && (editControl[0]=false)"
                                 v-model="editControl[1]">{{$i18n.t('btnControl./shop.editMenu')}}
                    </el-checkbox>
                </div>
            </div>
            <div class="topWrapper" v-if="editControl[0]">
                <el-form v-if="userInfo.authBtn.includes('/platform/set')" :size="customStyle.size" label-width="80px"
                         ref="validateFormShop_1" class="outerForm" :model="sendFormData.shop"
                         :rules="rules.shop">
                    <el-form-item label="商家" prop="name">
                        <el-input clearable placeholder="请输入商家名称" v-model="sendFormData.shop.name"
                                  autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="标识" prop="sign">
                        <el-input clearable placeholder="请输入商家标识" v-model="sendFormData.shop.sign"
                                  autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                        <el-radio-group v-model="sendFormData.shop.type">
                            <el-radio-button :label="0">CODE</el-radio-button>
                            <el-radio-button :label="1">名称</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label-width="20px">
                        <el-button type="primary" @click="handleSave('platform_1')">保 存</el-button>
                    </el-form-item>
                </el-form>
                <el-form :size="customStyle.size" v-if="userInfo.authBtn.includes('/tag/set')" label-width="80px"
                         ref="validateFormClassify" class="outerForm" :model="sendFormData.classify"
                         :rules="rules.classify">
                    <el-form-item label="分类" prop="tag">
                        <el-input clearable placeholder="请输入分类" v-model="sendFormData.classify.tag"
                                  autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label-width="20px">
                        <el-button type="primary" @click="handleSave('classify')">保 存</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="topWrapper" v-if="editControl[1]">
                <el-form :size="customStyle.size" label-width="80px" ref="validateFormOrder"
                         class="outerForm flexFormWrap" :model="sendFormData.order"
                         :rules="rules.order">
                    <div class="left">
                        <el-form-item label="CODE" prop="code">
                            <el-input clearable placeholder="请输入菜单CODE" v-model="sendFormData.order.code"
                                      autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="名称" prop="name">
                            <el-input clearable placeholder="请输入菜单名称" v-model="sendFormData.order.name"
                                      autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="价格" prop="price">
                            <el-input clearable placeholder="请输入菜单价格" type="number"
                                      v-model.number="sendFormData.order.price"
                                      autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label-width="20px">
                            <el-button type="primary" @click="handleSave('order')">保 存</el-button>
                        </el-form-item>
                    </div>
                    <el-form-item>
                        <el-button :type="isShopUse?'danger':'primary'"
                                   v-if="userInfo.authBtn.includes('/food/startUse')" plain @click="handleUse()">
                            {{$i18n.t('btnControl./shop.useMenu')[isShopUse]}}
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <!--            <el-button icon="el-icon-plus" type="primary" :size="customStyle.size" @click="dialogVisible=true">新增拼单</el-button>-->
        </header>
        <el-dialog append-to-body
                   v-if="dialogVisible"
                   :close-on-click-modal="false"
                   :title="`${(currentShop || {label:''}).label}菜单上传`"
                   :visible.sync="dialogVisible"
                   width="60%"
        >
            <upload :sign="activeShop"></upload>
        </el-dialog>
        <order-info :platformData="platformData" :orderData="orderData"></order-info>
        <el-table
            :data="tableData"
            border
            stripe
        >
            <el-table-column
                prop="code"
                label="CODE">
                <template #default="scope">
                    {{scope.row.code || '--'}}
                </template>
            </el-table-column>
            <el-table-column
                prop="name"
                label="名称">
            </el-table-column>
            <el-table-column
                prop="tag"
                label="分类">
            </el-table-column>
            <el-table-column
                prop="price"
                label="价格">
            </el-table-column>
            <el-table-column
                min-width="120px"
                label="操作">
                <template #default="scope">
                    <div class="controlBth">
                        <el-popover
                            placement="bottom"
                            width="160"
                            v-model="visible[scope.$index]">
                            <p>选择点餐时间？</p>
                            <p class="statusWrap flexWrap" v-if="scope.row.code || scope.row.name">
                                <span>状态：</span>
                                <el-radio-group size="mini" v-model="statusList[scope.$index]">
                                    <el-radio-button :label="1">修改</el-radio-button>
                                    <el-radio-button :label="0">添加</el-radio-button>
                                </el-radio-group>
                            </p>
                            <div style="text-align: center">
                                <el-button v-for="(i,index) in orderTimeMap" :key="i" size="mini" type="primary"
                                           @click="handleOrder(index,scope.row,scope.$index)">{{i}}
                                </el-button>
                            </div>
                            <el-button size="mini" slot="reference" type="primary" plain>点击下单</el-button>
                        </el-popover>
                        <el-button size="mini" class="starWrap" plain
                                   :icon="currentStartMenus.includes(scope.row.code)?'el-icon-star-on':'el-icon-star-off'"
                                   @click="handleStar(scope.row.code)"></el-button>
                        <el-button size="mini" @click="handleHide(scope.row)">隐藏</el-button>
                        <el-button size="mini" v-if="editControl[1]" type="danger" plain
                                   @click="rowDelete({platform:activeShop,tag:scope.row.tag,code:scope.row.code},`确认删除 ${scope.row.name}`,true)">
                            删 除
                        </el-button>

                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import OrderInfo from '@/components/order-info'
import Upload from '@/components/upload'
import {setTag, getTag, delTag, setPlatform, delPlatform} from '@/api/tag'
import {getFood, setFood, delFood, startUse} from '@/api/food'
import {setMenuStatus, setOrderStar} from '@/api/user'
import {setOrder, getOrder, orderCountDown} from '@/api/order'
import moment from 'moment'
import sortBy from 'lodash/sortBy'
import tableMixin from '@/mixins/table'
import {mapGetters} from "vuex";
import isUndefined from "lodash/isUndefined";

const evil = window.eval;
export default {
    name: "home",
    mixins: [tableMixin],
    components: {
        OrderInfo,
        Upload
    },
    data() {
        const validateSign = (rule, value, callback) => {
            if (!/^[a-zA-z]+$/.test(value)) {
                console.log(value)
                callback(new Error('标识只能输入纯英文字母'));
            } else {
                callback();
            }
        }
        const validateCode = (rule, value, callback) => {
            if (!/^[a-zA-Z\d]+$/.test(value)) {
                console.log(value)
                callback(new Error('CODE只能输入字母和数字'));
            } else {
                callback();
            }
        }
        return {
            dialogVisible: false,
            tagData: [],
            platformData: [],
            orderData: [],
            visible: [],
            statusList: [],
            editControl: [false, false],
            activeShop: '',
            activeTab: '全部',
            orderType: [],
            sendFormData: {
                classify: {
                    platform: '',
                    tag: ''
                },
                shop: {
                    name: '',
                    sign: '',
                    step: '',
                    type: 0,
                },
                order: {
                    price: '',
                    name: '',
                    tag: '全部',
                    code: '',
                    platform: '',
                }
            },
            gertTableDataDelay: true,
            rules: {
                shop: {
                    step: [
                        {required: true, message: '请输入商家起送价', trigger: 'blur'},
                    ],
                    name: [
                        {required: true, message: '请输入商家名称', trigger: 'blur'},
                    ],
                    sign: [
                        {required: true, message: '请输入商家标识', trigger: 'blur'},
                        {validator: validateSign, trigger: 'blur'}
                    ],
                    type: [
                        {required: true, message: '请选择商家类型', trigger: 'blur'},
                    ]
                },
                classify: {
                    tag: [
                        {required: true, message: '请输入分类', trigger: 'blur'},
                    ]
                },
                order: {
                    /*tag: [
                        { validator: validateSelect, trigger: 'blur' }
                    ],
                    platform: [
                        { required: true, message: '请选择点餐平台', trigger: 'blur' },
                    ],*/
                    name: [
                        {required: true, message: '请输入菜单名称', trigger: 'blur'},
                    ],
                    price: [
                        {required: true, message: '请输入菜单价格', trigger: 'blur'},
                    ],
                    code: [
                        {required: true, message: '请输入菜单code', trigger: 'blur'},
                        {validator: validateCode, trigger: 'blur'}
                    ]
                }
            }
        }
    },
    watch: {
        orderStatusInfo(v) {
            this.getTableData()
            if (!v[this.userInfo.username]) {
                this.getMyOrder()
            }
        }
    },
    computed: {
        currentStartMenus() {
            return this.starOrderMenus && this.starOrderMenus[this.activeShop] || []
        },
        currentShop(){
            return this.platformData.find(i => i.value === this.activeShop)
        },
        isShopUse() {
            return (this.currentShop || {isReady: 0}).isReady
        },
        ...mapGetters([
            'orderTimeMap',
            'userOrder',
            'statusData',
            'starOrderMenus',
            'orderTimeControl',
            'ioAwaitTime',
            'hideOrderMenus',
            'orderStatusInfo'
        ])
    },
    created() {
        //关闭页面异常订单风控
        this.getTag({type: 0}).then(data => {
            this.activeShop = data[0] && data[0].value
            if (this.activeShop) {
                this.sendFormData.classify.platform = this.activeShop
                this.sendFormData.order.platform = this.activeShop
                this.getTag({type: 1})
                this.getTableData()
            }
        })
        this.getMyOrder()
    },
    methods: {
        evil,
        handleUpload() {
            this.dialogVisible = true
        },
        handleUse() {
            this.showConfirm(this.isShopUse ?
                '取消使用后将开启订单审核，用户可自定义点餐，审核通过后用户菜单将写入该平台下的菜单中' :
                '开始使用后只能使用该商家分类下存在的菜单，确认该商家分类下已添加全部菜单？').then(() => {
                const name = (this.platformData.find(i => i.value === this.activeShop) || {}).label
                startUse({platform: this.activeShop, name}).then(res => {
                    this.getTag({type: 0})
                    this.$message.success(res.msg)
                })
            })
        },
        tableCallback() {
            const hideCode = (this.hideOrderMenus && this.hideOrderMenus[this.activeShop] || []).map(i => i.code);
            const result = this.tableData.filter(i => !hideCode.includes(i.code)).map(item => {
                let index = this.currentStartMenus.findIndex(i => i === item.code)
                if (index > -1) {
                    //找到后排序值按收藏顺序,后面收藏的在前面
                    item.sort = -index
                }
                return item
            });
            this.tableData = sortBy(result, 'sort')
            this.statusList = Array.from({length: this.tableData.length}).fill(1)
        },
        handleStar(code) {
            setOrderStar({platform: this.activeShop, code, username: this.userInfo.username}).then(res => {
                // hideOrderMenus
                this.$message.success(res.msg)
                this.$store.commit('user/SET_STAR_MENUS', res.data)
                this.getTableData()
            })
        },
        handleHide(item) {
            const username = this.userInfo.username
            setMenuStatus({item, username, platform: this.activeShop}).then(res => {
                // hideOrderMenus
                this.$message.success(res.msg)
                this.$store.commit('user/SET_HIDE_MENUS', res.data)
                this.getTableData()
            })
        },
        getMyOrder() {
            const username=this.userInfo.username;
            getOrder({username}).then(res => {
                this.orderData = res.data
                const item = this.orderData[0] || {}
                //剩余时间同步问题
                if(!isUndefined(item.status)){
                    if(!item.status){
                        this.setCountDown(username)
                        const startTime = this.orderTimeControl.startTime
                        const seconds = (new Date()).getTime() - startTime
                        const durationTime = moment.duration(seconds).seconds()
                        //相差秒数
                        const remainTime = this.orderTimeControl.orderTimeLimit - durationTime * 1000
                        remainTime >= 0 && this.$store.commit('exclude/SET_COUNT_DOWN', remainTime)
                    }else {
                        this.userOrder[username] && this.$store.commit('exclude/SET_HAD_USER',[username,0])
                    }
                }
            })
        },
        handleOrder(type, row, index) {
            let {price, code, name} = row
            let orderInfo;
            if (!type) {
                //上午
                orderInfo = {
                    orderType: 1,
                    username: this.userInfo.username,
                    price, code, name, type,
                    status: this.statusList[index],
                    platform: this.activeShop
                }
            } else {
                //下午
                orderInfo = {
                    orderType: 1,
                    username: this.userInfo.username,
                    price, code, name, type,
                    status: this.statusList[index],
                    platform: this.activeShop
                }
            }
            setOrder(orderInfo).then(res => {
                this.$message.success(res.msg)
                this.$set(this.visible, index, false)
                this.getMyOrder()
            })
        },
        async setCountDown(senduser) {
            if(!this.userOrder[senduser]){
                await setTimeout(async () => {
                    await orderCountDown({senduser}).then(res => {
                        const {orderTimeLimit, startTime} = res.data
                        this.$store.commit('system/SET_ORDER_TIME_LIMIT', {orderTimeLimit, startTime})
                        this.$store.commit('exclude/SET_HAD_USER',[senduser,1])
                    })
                }, this.ioAwaitTime)
            }
        },
        rowDeleteApi(data) {
            return delFood({tag: this.activeTab, platform: this.activeShop, ...data})
        },
        rowSaveApi(type) {
            const params=this.currentShop && type!=='platform_1'?{
                name:this.currentShop.label,
                sign:this.currentShop.value,
                type:this.currentShop.type,
            }:{};
            return this.editControl[0] ? (type.includes('platform') ? setPlatform({...this.sendFormData.shop,...params}) : setTag(this.sendFormData.classify)) : setFood(this.sendFormData.order)
        },
        tableApi() {
            return getFood({tag: this.activeTab, platform: this.activeShop})
        },
        handleClick(tab, isTag) {
            // this.editControl[0]?getTag({platform: this.activeShop}):
            if (!isTag) {
                //重置
                this.activeTab = '全部'
                this.sendFormData.order.tag = '全部'
                this.sendFormData.classify.platform = tab.name
                this.sendFormData.order.platform = tab.name
                // this.getTag({type: 0})
                this.getTag({type: 1})
            } else {
                this.sendFormData.order.tag = tab.name
            }
            this.getTableData()
        },
        getTag(data) {
            return getTag({platform: this.activeShop, ...data}).then(res => {
                if (!data.type) {
                    this.platformData = res.data
                } else {
                    this.tagData = res.data
                }
                return Promise.resolve(res.data)
            })
        },
        handleRemove(data, type) {
            const name = type === 'platform' ? (this.platformData.find(i => i.value === data.platform) || {}).label : data.tag
            this.showConfirm(`确认删除${data.platform ? `商家` : `分类`}${name}？`).then(() => {
                if (type === 'platform') {
                    delPlatform({name, ...data}).then(res => {
                        this.$message.success(res.msg)
                        this.getTag({type: 0})
                    })
                } else {
                    delTag({platform: this.activeShop, ...data}).then(res => {
                        this.$message.success(res.msg)
                        this.getTag({type: 1})
                    })
                }
            })
        },
        handleSave(type) {
            switch (type) {
                case 'platform_0':case 'platform_1': {
                    const index=type.split('_')[1]
                    this.$refs[`validateFormShop_${index}`].validate((valid) => {
                        valid && this.rowSaveApi(type).then(res => {
                            this.$message.success(res.msg)
                            this.getTag({type: 0})
                            this.$refs[`validateFormShop_${index}`].resetFields()
                        })
                    })
                    break
                }
                case 'classify': {
                    this.$refs.validateFormClassify.validate((valid) => {
                        valid && this.rowSaveApi().then(res => {
                            this.$message.success(res.msg)
                            this.getTag({type: 1})
                            this.$refs.validateFormClassify.resetFields({
                                platform: this.sendFormData.classify.platform
                            })
                        })
                    })
                    break
                }
                case 'order': {
                    //获取价格,code等
                    if (this.sendFormData.order.tag === '全部') {
                        return this.$message.error('请在其它（非全部）分类下添加菜单')
                    }
                    this.$refs.validateFormOrder.validate((valid) => {
                        this.sendFormData.order.code = this.sendFormData.order.code.toUpperCase()
                        valid && this.rowSave(this.sendFormData.order).then(res => {
                            this.$refs.validateFormOrder.resetFields()
                        })
                    })
                    break
                }
                default:
                    break
            }

        }
    }
}
</script>

<style scoped lang="scss">
.topWrapper {
    flex-wrap:wrap;
    display:flex;
    justify-content: space-between;
    .outerForm {
        margin-bottom:20px;
    }
    &:empty {
        display:none;
    }
    .left {
        display:flex;
    }
}
> > > .starWrap i {
    color:#409EFF;
}
> > > .balanceInfoWrap {
    p {
        margin:8px 0 !important;
    }
}
.flexFormWrap {
    width:100%;
    justify-content:space-between;
}
.formLine {
    width:100px;
}
> > > .el-popover {
    display:none;
    button {
        color:#409EFF;
        background:#ecf5ff;
        border-color:#b3d8ff;
    }
}


.tabEditWrapper {
    display:flex;
    align-items:center;
    .el-tabs {
        flex:auto;
    }
    .tabSwitch {
        display: flex;
        align-items: center;
        margin-left:30px;
        .el-form {
            margin-right:20px;
        }
    }
}

.outerForm {
    display:flex;
    > > > .el-form-item {
        margin-bottom:0 !important;
        .el-form-item__content {
            display:flex;
            .el-input {
                width:160px;
            }
            .item {
                display:flex;
                span {
                    flex:none;
                    margin-right:10px;
                }
                &:last-child {
                    margin-left:10px;
                }
            }
        }
    }
}
.innerForm {
    .item {
        display:flex;
        border-bottom:1px solid #eee;
        padding:8px 10px;
        span {
            flex:none;
            margin-right:30px;
        }
        &:last-child {
            border:none;
        }
    }
}
> > > .el-table__row {
    .orderItem {
        border-bottom:1px solid #eee;
        padding:8px 10px;
        &:last-child {
            border:none;
        }
    }
}

</style>
